import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import store from '@/store'
import { transParams } from '@/utils/ruoyi'

const isReLogin = { show: false }

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

/**
 * 请求拦截器
 */
service.interceptors.request.use(config => {
  console.log('requestInterceptor-request:config', config)
  const notToken = (config.headers || {}).notToken === true
  if (getToken() && !notToken) {
    config.headers.Authorization = 'Bearer ' + getToken()
  }
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + transParams(config.params)
    url = url.slice(0, -1)
    config.params = {}
    config.url = url
  }
  return config
}, error => {
  Message({
    message: error,
    type: 'error',
    duration: 5 * 1000
  })
})

/**
 * 响应拦截器
 */
service.interceptors.response.use(res => {
  const code = res.data.code
  const msg = res.data.msg
  if (code === 401) {
    if (!isReLogin.show) {
      isReLogin.show = true
      MessageBox.confirm('登录状态已过期，请重新登录', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        isReLogin.show = false
        store.dispatch('Logout').then(() => {
          location.href = '/'
        })
      }).catch(() => {
        isReLogin.show = false
      })
    }

    return Promise.reject(new Error('无效的回话，或者会话已过期，请重新登录'))
  } else if (code === 500) {
    Message({
      message: msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(new Error(msg))
  } else if (code !== 200) {
    return Promise.reject(new Error('err'))
  } else {
    return res.data
  }
}, error => {
  console.log(error)
  let { message } = error
  if (message.includes('timeout')) {
    message = '请求超时，请稍后重试'
  } else if (message.includes('Request failed with status code')) {
    message = '系统接口' + message.substr(message.length - 3) + '异常'
  }
  Message({
    message: message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
})
export default service
